<?php

//为解决合并问题，先暂时把功能把到这个文件中，将来再合并过来
require_once APPLICATION_PATH . '/modules/default/controllers/MemberExtController.php';

/*
 * 会员中心
 */

class MemberController extends MemberExtController {

    public function init() {

        parent::init();
        //$this->_helper->redirector('login','user');
        //加载公共js
        $this->appendScript('/js/jquery.min.js')->appendScript('/js/jquery.validate.min.js')->appendScript('/js/messages_cn.js')->appendScript('/js/uuch.js');
        $this->view->menuId = $this->getRequest()->getParam('action');
        $userid = $this->currentUser()->Id;

        $uCount = array();

        //获取用户仓库总数
        $utemp = Application_Model_StoreItem::getItemCount($userid, Application_Model_StoreItem::STATUS_InStored);
        if ($utemp == null) {
            $utemp = 0;
        }
        $uCount["store"] = $utemp;

        //入报入库
        $utemp = Application_Model_ingstore::getItemCount($userid, 0);
        if ($utemp == null) {
            $utemp = 0;
        }
        $uCount["ingstore"] = $utemp;

        //运单总数
        $utemp = Application_Model_wayBillItem::getItemCount($userid, -1);
        if ($utemp == null) {
            $utemp = 0;
        }
        $uCount["will"] = $utemp;


        $this->view->user = $this->currentUser();

        $this->view->account = Application_Model_UserAccount::addAccount($userid);
        //订单总数
        $uCount["order"] = Application_Model_Order::getUncomplate($userid);
        $uCount['mail'] = $this->view->mainCount;


        //优惠券
        $utemp = Application_Model_Coupon::getItemCount($userid, -1);
        if ($utemp == null) {
            $utemp = 0;
        }

        $uCount["Coupon"] = $utemp;

        //上门取件
        $utemp = Application_Model_VisitingServer::getCountByUserId($userid);
        if ($utemp == null) {
            $utemp = 0;
        }
        $uCount["visiting"] = $utemp;
        $this->view->uCount = $uCount;
    }

    public function storeaddressAction() {
        
    }

    /*
     * 我的仓库主页
     */

    public function storehomeAction() {
        $this->setTitle('我的云仓库 | 集中管理，集中配送，更能节省运费');
        $this->appendScript('/js/jquery.min.js')->appendScript('/js/clip/zeroclipboard.js');
        $this->appendCss('/css/Share.css'); //    
        $this->appendCss('/css/home/warehouse.css'); //   

        $this->view->storeAddress = Application_Model_Config::getStoreAddress()->Value;
        //购物车信息
        $this->view->cart = Application_Model_Cart::current();
    }

    //预报入库
    /*
     * 预报入库
     */
    public function instoreAction() {
        $this->setTitle('预报入库 | 无需代购，自主买遍国货');
        $this->appendCss('/css/home/warehouse.css'); //    
        //$this->appendCss('/css/express.css');
        $request = $this->getRequest();

        $words = array();
        for ($i = 0; $i < 26; $i++) {
            $words [] = chr(65 + $i);
        }
        $this->view->words = $words;

        $expressid = $this->getSafeParam('expressid');
        $this->view->expressno = $this->getSafeParam('expressno');
        $this->view->name = $this->getSafeParam('name');

        $express = Application_Model_shipType::load($expressid);
        if ($express != NULL) {
            $this->view->expressname = $express->Name;
            $this->view->expressid = $express->Id;
        } else {
            $this->view->expressname = '申通';
            $this->view->expressid = '9';
        }

        if ($request->isPost()) {
            //提交
            $userid = $this->currentUser()->Id;

            $urls = $this->getSafeParam("url");

            //$shipTypes= explode(",",$this->getSafeParam("shipType"));

            $newItem = new Application_Model_ingstore();
            $newItem->name = $this->getSafeParam("name");
            $newItem->type = $this->getSafeParam("hasDetail");
            $newItem->shipTypeid = $this->getSafeParam('expressid'); //?
            $newItem->shipType = $this->getSafeParam('expressname');
            $newItem->shipNo = $this->getSafeParam("logistics");
            $newItem->url = '';  //商品信息
            $newItem->remark = $this->getSafeParam("remark");
            $newItem->createtime = date('Y-m-d H:i:s');
            //$newItem->intime=$this->getSafeParam("intype");
            $newItem->state = 0;
            $newItem->userid = $userid;
            if ($newItem->validShipNo()) {
                $newItem->save();


                $num = 0;

                /*
                  foreach ($urls as $urlItem) {
                  if($urlItem && $urlItem!=''){
                  $addItem=new Application_Model_ingstoreproduct();
                  $addItem->ingstoreid=$newItem->id;
                  $addItem->url=$urlItem;
                  $addItem->image='';
                  $addItem->state=0;
                  $addItem->save();
                  $num++;
                  }
                  }
                 * 
                 */

                $event = new Application_Model_event();
                $event->userid = $userid;
                $event->username = $this->currentUser()->nikename;
                $event->opType = '预报入库';
                $event->opTime = date('Y-m-d H:i:s');
                $event->opCaption = '预报一个包裹：来源【' . $this->getSafeParam("intype") . '】';
                $event->url = '';
                $event->save();

                $this->view->newItem = $newItem;
                $this->view->addFlag = 1;
                $this->view->num = $num;
            } else {
                $this->view->addFlag = 2;
            }
        } else {
            $this->view->storeAddress = Application_Model_Config::getStoreAddress()->Value; //仓库地址 
            $shipTypes = Application_Model_shipType::getbyType(1); //获取快递公司列表
            $this->view->shipTypes = $shipTypes;
        }
    }

    //我的仓库
    /**
     *  我的仓库
     */
    public function mystoreAction() {
        $this->setTitle('我的仓库 | 您的金牌仓库管家');
        //$this->appendCss('/css/Share.css'); //    
        $this->appendCss('/css/home/warehouse.css');
        $this->appendScript('/js/jquery.min.js');

        $start = $this->getSafeParam('start');
        if (!$start) {
            $start = 0;
        }
        $code = $this->getSafeParam('activityCode');
        if ($code && date("Y-m-d") >= Application_Model_RechargeBill::RechargeActivityStart && date("Y-m-d") <= Application_Model_RechargeBill::RechargeActivityEnd) {
            setcookie('activityCode', Uuch_Util::encryptString($code), 0, "/");
        }

        $userid = $this->currentUser()->Id;
        $this->view->stores = Application_Model_StoreItem::getMyStore($userid, $this->pageSize, $start);
        $selected = Application_Model_StoreItem::getMySelect($userid);

        $this->view->selected = array('count' => count($selected), 'weight' => Application_Model_StoreItem::getSumWeight($selected));
        $this->view->storelist = $this->view->stores['list'];
        $this->view->IsReceive = Application_Model_StoreItem::getByUserIdBarcode($userid, Application_Model_StoreItem::User_Barcode);
    }

    public function storedetailAction() {
        $this->setTitle('我的仓库 | 您的金牌仓库管家');
        $this->appendCss('/css/Share.css'); //    
        $this->appendCss('/css/home/warehouse.css');
        $this->appendScript('/js/jquery.min.js');
        $storeId = $this->getSafeParam("storeid");
        if ($storeId) {

            $storeItem = Application_Model_StoreItem::load($storeId);
            if ($storeItem->Userid != $this->currentUser()->Id) {
                $this->redirect('mystore', 'member');
                return;
            }

            $this->view->storeItem = $storeItem;
        } else {
            $this->redirect('mystore', 'member');
            return;
        }
    }

    /**
     * 仓库历史
     */
    public function storehistoryAction() {
        $this->setTitle('仓库历史记录');
        $this->appendCss('/css/Share.css')->appendCss('/css/home/warehouse.css')->appendScript('/js/jquery.min.js');

        $start = $this->getSafeParam('start');
        if (!$start) {
            $start = 0;
        }

        $stime = $this->getSafeParam('stime');
        if (!$stime)
            $stime = -3;

        $etime = $this->getSafeParam('etime');
        if (!$etime)
            $etime = 1;

        $this->pageSize = 10;
        $userid = $this->currentUser()->Id;
        $this->view->stores = Application_Model_StoreItem::getByFilter(NULL, $userid, NULL, NULL, Application_Model_StoreItem::STATUS_Sended, $this->pageSize, $start);

        $this->view->storelist = $this->view->stores['list'];
    }

    public function forecastlistAction() {
        $this->setTitle('我的仓库 | 预报列表 | 您的金牌仓库管家');
        $this->appendCss('/css/Share.css'); //    
        $this->appendCss('/css/home/warehouse.css'); //            
        $this->appendScript('/js/jquery.min.js');

        $oper = $this->getSafeParam('oper');
        if ($oper == "del") {
            $id = $this->getSafeParam("id");
            Application_Model_ingstore::cancel($id);
        }

        $start = $this->getSafeParam('start');
        if (!$start)
            $start = 0;

        $state = $this->getSafeParam('state');
        if (!$state)
            $state = 0;

        $stime = $this->getSafeParam('stime');
        if (!$stime)
            $stime = -3;

        $etime = $this->getSafeParam('etime');
        if (!$etime)
            $etime = 1;

        $this->pageSize = 10;

        $userid = $this->currentUser()->Id;
        $this->view->ingstores = Application_Model_ingstore::getByFilter(NULL, $userid, date('Y-m-d', strtotime("$stime months")), date('Y-m-d', strtotime("$etime months")), $state, $this->pageSize, $start);


        $this->view->ingstorelist = $this->view->ingstores['list'];
    }

    /**
     * 全部上门取件列表
     */
    public function visitinglistAction() {
        $this->setTitle('上门取件 | 悠奇仓库');
        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/warehouse.css');
        $this->appendCss('/css/home/shangmen.css');
        $this->appendScript('/js/jquery.min.js');

        $start = $this->getSafeParam('start');
        if (!$start)
            $start = 0;
        $this->pageSize = 8;
        if ($this->getSafeParam("id")) {
            $visitingItem = Application_Model_VisitingServer::load($this->getSafeParam("id"));
            if ($visitingItem->userId != $this->currentUser()->Id) {
                $this->redirect('visitinglist', 'member');
                return;
            }
            $oper = $this->getSafeParam("oper");
            if ($oper == "cancel") {
                $this->view->ma = $visitingItem->cancelVisiting();
            }
            if ($oper == "del") {
                $this->view->ma = $visitingItem->delVisiting();
            }
        }
        $visitingSearch = new Application_Model_Filter_VisitingSearch();
        $userId = $this->currentUser()->Id;
        $visitingSearch->userId = $userId;
        $this->view->visitingAll = Application_Model_VisitingServer::getVisitingAll($visitingSearch, $this->pageSize, $start);
        $this->view->visitinglist = $this->view->visitingAll['list'];
    }

    /**
     * 完成的上门取件
     */
    public function vsachieveAction() {
        $this->setTitle('上门取件 | 悠奇仓库');
        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/warehouse.css');
        $this->appendCss('/css/home/shangmen.css');
        $this->appendScript('/js/jquery.min.js');

        $start = $this->getSafeParam('start');
        if (!$start)
            $start = 0;
        $this->pageSize = 8;
        if ($this->getSafeParam("id")) {
            $visitingItem = Application_Model_VisitingServer::load($this->getSafeParam("id"));
            if ($visitingItem->userId != $this->currentUser()->Id) {
                $this->redirect('visitinglist', 'member');
                return;
            }
            $oper = $this->getSafeParam("oper");
            if ($oper == "cancel") {
                $this->view->ma = $visitingItem->cancelVisiting();
            }
            if ($oper == "del") {
                $this->view->ma = $visitingItem->delVisiting();
            }
        }
        $visitingSearch = new Application_Model_Filter_VisitingSearch();
        $userId = $this->currentUser()->Id;
        $visitingSearch->userId = $userId;
        $visitingSearch->status = Application_Model_VisitingServer::STATUS_InStore;
        $this->view->visitingAll = Application_Model_VisitingServer::getVisitingAll($visitingSearch, $this->pageSize, $start);
        $this->view->visitinglist = $this->view->visitingAll['list'];
    }

    /*
     * 取消的上门取件
     */

    public function vscancelAction() {
        $this->setTitle('上门取件 | 悠奇仓库');
        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/warehouse.css');
        $this->appendCss('/css/home/shangmen.css');
        $this->appendScript('/js/jquery.min.js');

        $start = $this->getSafeParam('start');
        if (!$start)
            $start = 0;
        $this->pageSize = 8;
        if ($this->getSafeParam("id")) {
            $visitingItem = Application_Model_VisitingServer::load($this->getSafeParam("id"));
            if ($visitingItem->userId != $this->currentUser()->Id) {
                $this->redirect('visitinglist', 'member');
                return;
            }
            $oper = $this->getSafeParam("oper");
            if ($oper == "cancel") {
                $this->view->ma = $visitingItem->cancelVisiting();
            }
            if ($oper == "del") {
                $this->view->ma = $visitingItem->delVisiting();
            }
        }
        $visitingSearch = new Application_Model_Filter_VisitingSearch();
        $userId = $this->currentUser()->Id;
        $visitingSearch->userId = $userId;
        $visitingSearch->status = Application_Model_VisitingServer::STATUS_Cancel;
        $this->view->visitingAll = Application_Model_VisitingServer::getVisitingAll($visitingSearch, $this->pageSize, $start);
        $this->view->visitinglist = $this->view->visitingAll['list'];
    }

    /**
     * 上门取件详情
     */
    public function vsdetailAction() {
        $this->setTitle('上门取件 | 集中管理，集中配送，更能节省运费');

        $this->appendCss('/css/Share.css'); //            
        $this->appendCss('/css/home/shangmen.css');
        $this->appendCss('/css/home/waybill.css'); // 

        $id = $this->getSafeParam('id');
        //获取运单信息
        if ($id) {
            $visitingItem = Application_Model_VisitingServer::load($id);
            if ($visitingItem->userId != $this->currentUser()->Id) {
                $this->redirect('visitinglist', 'member');
                return;
            }
            $oper = $this->getSafeParam("oper");
            if ($oper == "cancel") {
                $this->view->ma = $visitingItem->cancelVisiting();
            }
            $this->view->ma = $this->getSafeParam("ma");
            $this->view->vsDetail = $visitingItem;
            if ($visitingItem->inlandLogistics != "" && ($visitingItem->interior >= Application_Model_VisitingServer::Interior_Delivery && $visitingItem->interior != Application_Model_VisitingServer::Interior_ShipOutTime)) {
                $this->view->logisticsUrl = Application_Model_wayBillItem::expressUrl("shunfeng", $visitingItem->inlandLogistics);
            }
            $this->view->issuedetail = Application_Model_problem::byissue($id, Application_Model_problem::TYPE_VISITING);
            $this->view->problemWay = Application_Model_ProblemWay::getByTypeWayId($id, Application_Model_ProblemWay::Type_Visiting);
            $this->view->scheduledetail = Application_Model_ProblemSchedule::getTypeWayIdBySchedule($id, Application_Model_ProblemSchedule::Type_Visiting);
        } else {
            $this->redirect('visitinglist', 'member');
        }
    }

    public function affirmvsproblemAction() {
        $vsId = $this->getSafeParam("id");
        $content = $this->getSafeParam("content");
        $visitingItem = Application_Model_VisitingServer::load($vsId);
        if ($visitingItem->problem != Application_Model_VisitingServer::Problem_Cancel && $visitingItem->interior != Application_Model_VisitingServer::STATUS_Launch) {
            if (htmlspecialchars($content) != "") {
                $visitingItem->addProblemUser(htmlspecialchars($content));
            }
        }
        $this->_redirect('/member/vsdetail/ma/3/id/' . $vsId);
    }

    /**
     * 运单管理
     */
    public function waybillAction() {
        $this->setTitle('运单管理 |  集中管理，集中配送，更能节省运费');
        $this->appendCss('/css/Share.css'); //    
        $this->appendCss('/css/home/waybill.css'); // 

        $oper = $this->getSafeParam("oper");
        if ($oper == "cancel") {
            //撤消运单
            $id = $this->getSafeParam("id");
            $way = Application_Model_wayBillItem::load($id);
            if ($way->UserId != $this->currentUser()->Id) {
                $this->redirect('waybill', 'member');
                return;
            }
            if ($way->Status == Application_Model_wayBillItem::STATUS_Processing || $way->Status == Application_Model_wayBillItem::STATUS_WaitPay) {
                $way->cancelWay();
                $this->view->type = 'cancel';
                $this->view->way = $way;
            }
            //Application_Model_wayBillItem::cancel($id);
            //撤消仓库单
            //Application_Model_StoreItem::cancelForWay($id);
        } else if ($oper == "sign") {
            //确认收货
            $id = $this->getSafeParam("id");
            $result = Application_Model_wayBillItem::sign($id);
            //双十一活动处理 begin
            if ($result) {
                $way = Application_Model_wayBillItem::load($id);
                if (time() > strtotime('2014-11-11') && time() < strtotime('2014-11-27') && $way->dateCreated > '2014-11-11') {                 
                    $userId = $way->UserId;
                    $recharge_user_array = explode("\t", file_get_contents('../data/double_eleven_recharge_user.txt')); 
                    if (!in_array($userId, $recharge_user_array)) {
                        $share_user_array = explode("\t", file_get_contents('../data/double_eleven_share_user.txt'));   
                        if (in_array($userId, $share_user_array)) {
                            $wayMoney = $way->shipMoney;
                            $money = 0;
                            if ($wayMoney >= 200 && $wayMoney < 500) {
                                $money = 6;
                            } elseif ($wayMoney >= 500 && $wayMoney < 800) {
                                $money = 15;
                            } elseif ($wayMoney >= 800 && $wayMoney < 1200) {
                                $money = 40;
                            } elseif ($wayMoney >= 1200) {
                                $money = 96;
                            };
                            if ($money > 0) {
                                Application_Model_User::editmoney($userId, $money, '国际运单' . $way->billNo . '双十一活动返现', '', 'recharge');
                                file_put_contents('../data/double_eleven_recharge_user.txt', $userId . "\t", FILE_APPEND);
                            }
                        }
                    }                       
                }
            }
            //双十一活动处理 end
        }

        $start = $this->getSafeParam('start');
        if (!$start) {
            $start = 0;
        }

        $this->pageSize = 10;

        $userid = $this->currentUser()->Id;
        $this->view->waybills = Application_Model_wayBillItem::getByFilter(NULL, $userid, date('Y-m-d', strtotime('-10 months')), date('Y-m-d', strtotime('+10 days')), null, $this->pageSize, $start);

        $this->view->waybilllist = $this->view->waybills['list'];
    }

    /**
     * 验证优惠券
     */
    public function validatecouponAction() {
        $no = $this->getSafeParam('couponno');
        $money = $this->getSafeParam('money');
        $userid = $this->currentUser()->Id;
        $password = $this->getSafeParam('password');
        $shipId = $this->getSafeParam("shipId");
        $coupon = Application_Model_Coupon::getByNo($no);
        $result = $coupon->Validate($userid, $money, $password, $shipId);
        $this->json($result);
    }

    public function waybillshow() {
        $ids = $this->getSafeParam('ids');
        $this->view->ids = $ids;
        $Stores = Application_Model_StoreItem::getByids($ids);
        $userid = $this->currentUser()->Id;
        if (empty($Stores)) {
            //跳转到运单列表页
            $this->_redirector = $this->_helper->getHelper('Redirector');
            $this->_redirector->gotoUrl('/member/mystore');
            return;
        }

        //$productCount = 0; 
        $weightCount = 0;
        //$timeOutCount = 0;

        $volumWeight = 0;

        foreach ($Stores as $item) {
            if ($item->WayId) {
                $this->redirect('mystore', 'member');
                return;
            }

            $weightCount+=$item->weight; //计算总重量

            if ($item->VolumeWeight) {
                $volumWeight += $item->VolumeWeight;
            } else {
                $volumWeight += $item->Weight;
            }
        }
        $packWeight = Uuch_Util::getPackage($weightCount);

        $storeCount = count($Stores);

        $this->view->adds = Application_Model_address::getbyuid($userid);
        //获取默认邮寄地址
        $cityId = 1;
        if (count($this->view->adds) == 0) {
            $address = new Application_Model_address();
            $this->view->defaultAddress = $address;
        } else {
            $this->view->defaultAddress = $this->view->adds[0];
            $cityId = $this->view->defaultAddress->State;
        }

        $prices = Application_Model_Express::getPricesByCity($cityId);
        $this->view->prices = $prices;

        //获取配送方式
        //$shipFeeConfigitems = Application_Model_shipFeeConfig::getbyCityid(1);
        //页面需要展示内容       
        $this->view->Stores = $Stores;
        $this->view->storeCount = $storeCount; //库存数
        $this->view->weightCount = $weightCount; //总重量
        $this->view->packWeight = $packWeight; //包裹重量

        $this->view->volumeWeight = $volumWeight;
        //
        //$this->view->productCount = $productCount; //商品总数
        //$this->view->timeOutCount = $timeOutCount; //超时费用                    
        //$this->view->shipFeeConfigitems = $shipFeeConfigitems; //配送方式
        //自发包裹数量 
        //购物包裹数量
        //收货信息


        $words = array();
        for ($i = 0; $i < 26; $i++) {
            $words [] = chr(65 + $i);
        }
        $this->view->words = $words;

        $this->view->coupons = Application_Model_Coupon::getByUser($userid, Application_Model_Coupon::STATUS_OK);
    }

    public function waybillinfoAction() {
        $this->setTitle('运单管理 |  集中管理，集中配送，更能节省运费');

        $this->appendCss('/css/Share.css'); //            

        $this->appendCss('/css/home/waybill.css'); // 

        $id = $this->getSafeParam('id');
        //获取运单信息
        if ($id) {

            $waybill = Application_Model_wayBillItem::load($id);
            if ($waybill->UserId != $this->currentUser()->Id) {
                $this->redirect('waybill', 'member');
                return;
            }

            $this->view->ma = $this->getSafeParam("ma");
            $this->view->waybill = $waybill;
            $this->view->issuedetail = Application_Model_problem::byissue($id, Application_Model_problem::TYPE_BILL);
            $this->view->problemWay = Application_Model_ProblemWay::getByTypeWayId($id);
            $this->view->scheduledetail = Application_Model_ProblemSchedule::getTypeWayIdBySchedule($id);
        }
    }

    /**
     * 添加客户问题沟通
     */
    public function affirmproblemAction() {
        $billid = $this->getSafeParam("id");
        $content = $this->getSafeParam("content");
        $billItem = Application_Model_wayBillItem::load($billid);
        if ($billItem && $billItem->status != Application_Model_wayBillItem::STATUS_Complated && $billItem->status != Application_Model_wayBillItem::Interior_Cancel) {
            $billItem->addProblemUser(htmlspecialchars($content));
        }
        $this->_redirect('/member/waybillinfo/ma/1/id/' . $billid);
    }

    /*
     * 运单评论
     */

    public function evaluateAction() {
        $this->setTitle('运单管理 |  集中管理，集中配送，更能节省运费');
        $this->appendCss('/css/Share.css'); //    
        $this->appendCss('/css/evaluate.css'); // 
        $this->appendCss('/css/warehouse.css'); // 

        $id = $this->getSafeParam('id');
        if (!$id) {
            $this->_redirector = $this->_helper->getHelper('Redirector');
            $this->_redirector->gotoUrl('/member/waybill');
            exit;
        }

        $wayItem = new Application_Model_wayBillItem($id);
        if (!$wayItem || $wayItem->status != 100) {
            $this->_redirector = $this->_helper->getHelper('Redirector');
            $this->_redirector->gotoUrl('/member/waybill');
            exit;
        }
        $request = $this->getRequest();
        if ($request->isPost()) {
            $userid = $this->currentUser()->Id;

            $newItem = new Application_Model_comment();
            $newItem->userid = $this->currentUser()->Id;
            $newItem->username = $this->currentUser()->username;
            $newItem->area = ''; //区域
            $newItem->type = 0;
            $newItem->code = $wayItem->id;
            $newItem->logistics = $this->getSafeParam("logistics");
            $newItem->service = $this->getSafeParam("service");
            $newItem->comment = $this->getSafeParam("comment");
            $newItem->createtime = date('Y-m-d H:i:s');
            $newItem->parentid = 0;
            $newItem->points = 10;
            $newItem->save();
            //更新运单信息
            $wayItem->comment = $newItem->id;
            $wayItem->save();

            $this->_redirector = $this->_helper->getHelper('Redirector');
            $this->_redirector->gotoUrl('/member/waybill');
            exit;
        }


        $this->view->wayItem = $wayItem;
    }

    /**
     * 提现
     */
    public function withdrawAction() {
        $this->setTitle('我的帐户 |  提现');
        $start = $this->getSafeParam('start');
        if (!$start) {
            $start = 0;
        }
        $this->pageSize = 10;

        $this->appendCss('/css/home/rmb.css');
        $this->view->account = $this->currentUser()->Account;
        $this->view->history = $this->view->account->getMoneyChange(date('Y-m-d', strtotime('-1 years')), date('Y-m-d', strtotime('+1 days')), $this->pageSize, $start);
        $this->view->historyList = $this->view->history['list'];

        $request = $this->getRequest();
        if ($request->isPost()) {
            $ret = array(
                "ret" => 0,
                "msg" => ''
            );

            $withDrawMoney = $request->getParam('submit_withdraw');
            $state = $request->getParam('state');
            $logid = $request->getParam('logid');

            //写入UUCH_Cash
            $cash = new Application_Model_cash();
            $cash->Money = $withDrawMoney;
            $cash->CashTime = date('Y-m-d H:i:s', time());
            $cash->State = 0;
            $cash->Uid = $this->currentUser()->Account->Id;
            $cash->Logid = $logid;
            $cash->Remark = ($state == "5") ? "撤消" : "提现";
            $cash->save();

            //将充值记录表中状态置为2.   保存对象是否正确？
            $item = new Application_Model_UserAccountHistory($logid);
            $item->State = 5;
            $item->save();

            $ret['ret'] = 1;

            echo json_encode($ret);
            exit;
        }
    }

    public function canelwithdrawAction() {
        $this->setTitle('我的帐户 |  提现');
        $request = $this->getRequest();
        if ($request->isPost()) {
            $ret = array(
                "ret" => 0,
                "msg" => ''
            );

            $id = $request->getParam('id');

            //修改UUCH_Cash，根据状态(0)，logid获取 cash 对象
            $cash = Application_Model_cash::getByLogidAndState($id, 0);
            if ($cash) {
                $cash->State = -1;
                $cash->save();

                $logid = $cash->Logid;

                //将充值记录表中状态置为2.   保存对象是否正确？
                $item = new Application_Model_UserAccountHistory($logid);
                $item->State = 1;
                $item->save();

                $ret['ret'] = 1;
            }

            echo json_encode($ret);
            exit;
        }
    }

    /*
     * 退款列表
     */

    public function withdrawlistAction() {
        $this->setTitle('我的帐户 |  提现列表');
        $this->appendCss('/css/home/rmb.css');
        $this->view->account = $this->currentUser()->Account;
        $this->view->history = $this->view->account->getMoneyChange(date('Y-m-d', strtotime('-1 years')), date('Y-m-d', strtotime('+1 days')));
    }

    /*
     * 优惠券功能
     */

    public function couponAction() {
        $this->setTitle('我的帐户 |  优惠券功能');
        $this->appendCss('/css/home/coupon.css');


        $start = $this->getSafeParam('start');
        if (!$start)
            $start = 0;

        $status = $this->getSafeParam('status');
        if (!$status)
            $status = 1;
        $this->pageSize = 10;

        $userid = $this->currentUser()->Id;
        $couponSearch = new Application_Model_Filter_CouponSearch();
        $couponSearch->userId = $userid;
        $couponSearch->status = $status;
        $this->view->coupons = Application_Model_Coupon::getByFilter($couponSearch, $this->pageSize, $start);
        $couponSearch->status = Application_Model_Coupon::STATUS_OK;
        $couponSearch->dateType = "dateExpired";
        $couponSearch->startTime = date("Y-m-d H:i:s");
        $couponSearch->endTime = date('Y-m-d', strtotime('+3 months'));
        $this->view->payStatus = Application_Model_Coupon::getCountByStatus($couponSearch);
        $this->view->timesStatus = Application_Model_Coupon::getCountByStatus($couponSearch);

        $this->view->coupon = $this->view->coupons['list'];
        $this->view->status = $status;
    }

    public function pointAction() {
        $this->appendCss('/css/home/point.css');
    }

    public function refundAction() {
        $this->appendCss('/css/home/rmb.css');
    }

    /**
     * 支付宝充值码
     */
    public function alipaycodeAction() {
        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/alipaycode.css');

        $this->appendScript('/js/jquery.min.js');
        $this->appendScript('/js/jquery.validate.min.js');

        $this->setTitle('购买充值码');

        //暂时一致
        $request = $this->getRequest();
        if ($request->isPost()) {
            $currentUser = $this->currentUser();
            $currentUserAccount = $currentUser->Account;
            $user_money = $currentUserAccount->Money;

            $money = $request->getParam('money');
            $typeId = $request->getParam('type');
            //先判断卡是否
            $card = Application_Model_PayCodeCard::getFirstByType($typeId, 0);

            if ($card != null) {//库存足够
                //1获取卡信息
                $card->userID = $currentUser->Id;
                $card->state = 5;
                $card->userTime = date("Y-m-d H:i:s", time());
                $card->save();
                //2新增订单记录
                $addOrder = new Application_Model_PayCodeOrder();
                $addOrder->uid = $currentUser->Id; //用户ID   
                $addOrder->userName = $currentUser->nikename; //用户名 
                $addOrder->money = $money; //金额        
                $addOrder->cardid = $card->id; //授权卡序号  
                $addOrder->cardno = $card->cardNo; //授权卡号       
                $addOrder->verifyCode = $card->cardPwd; //授权密码
                $addOrder->typeid = $card->typeid; //所属类型   
                $addOrder->cardType = $card->cardType; //卡类型    
                $addOrder->createTime = date("Y-m-d H:i:s", time()); //创建时间 
                $addOrder->payTime = date("Y-m-d H:i:s", time()); //付款时间        
                $addOrder->url = ""; //相关地址
                $addOrder->state = 0; //状态         0：未付款 5、受理中 10：已付款  20：待充值  30：充值完成 100:撤消
                $addOrder->remark = ""; //备注
                $addOrder->save();
                $this->redirect('paying', 'pay', array('type' => Application_Model_PayBill::TYPE_ALI_CODE, 'id' => $addOrder->Id, 'count' => 1));
            } else {
                $this->view->message = "对不起,您选择的$money 元的卡已售完,请选择别的面值的卡号.";
            }
        }
    }

    /**
     * 代付款 
     */
    public function agentpayAction() {
        if(Application_Model_wayBillItem::getItemCount($this->currentUser()->Id, Application_Model_wayBillItem::STATUS_Complated) < 3) {
            $this->redirect('home', 'member');
            return;
        }
        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/replacerecharge.css');

        $this->appendScript('/js/jquery.min.js');
        $this->appendScript('/js/jquery.validate.min.js');

        $this->setTitle('代支付服务');
        $userId = $this->currentUser()->Id;
        if ($this->getRequest()->isPost()) {
            $userGrade = Uuch_Util::getUserGradeByUserId($userId);
//            if($userGrade >= Application_Model_AgentPay::Agent_UserGrade){
            $pay = new Application_Model_AgentPay();
            $pay->MemberId = $userId;
            $pay->PayMoney = $this->getSafeParam('money');
            $pay->Code = $this->getSafeParam('code');
            $pay->expressCompany = $this->getSafeParam('expressCompany');
            $pay->Remark = $this->getSafeParam('remark');
            $pay->Url = $this->getSafeParam('payurl');
            $pay->Type = $this->getSafeParam('paytype');
            $pay->ProcessFee = Application_Model_Config::getProcessFee()->Value;
            $pay->dateCreated = date('Y-m-d H:i:s', time());
            $pay->save();
            $this->redirect('paying', 'pay', array('type' => Application_Model_PayBill::TYPE_AGENT_PAY, 'id' => $pay->Id, 'count' => 1));
//            } else {
//                $this->view->ma = 1;
//            }
        }
    }

    /**
     * 移动卡支付 
     */
    public function cardpayAction() {
        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/cardpay.css');

        $this->appendScript('/js/jquery.min.js');
        $this->appendScript('/js/jquery.validate.min.js');

        $this->setTitle('购买移动卡');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $currentUser = $this->currentUser();

            $money = $request->getParam('money');

            $typeId = $request->getParam('type');


            //先判断卡是否
            $card = Application_Model_PayCodeCard::getFirstByType($typeId, 0);

            if ($card != null) {//库存足够
                //1获取卡信息
                $card->userID = $currentUser->Id;
                $card->state = 5;
                $card->userTime = date("Y-m-d H:i:s", time());
                $card->save();
                //2新增订单记录
                $addOrder = new Application_Model_PayCodeOrder();
                $addOrder->uid = $currentUser->Id; //用户ID   
                $addOrder->userName = $currentUser->nikename; //用户名 
                $addOrder->money = $money; //金额        
                $addOrder->cardid = $card->id; //授权卡序号  
                $addOrder->cardno = $card->cardNo; //授权卡号       
                $addOrder->verifyCode = $card->cardPwd; //授权密码
                $addOrder->typeid = $card->typeid; //所属类型   
                $addOrder->cardType = $card->cardType; //卡类型    
                $addOrder->createTime = date("Y-m-d H:i:s", time()); //创建时间 
                $addOrder->payTime = date("Y-m-d H:i:s", time()); //付款时间        
                $addOrder->url = ""; //相关地址
                $addOrder->state = 0; //状态         0：未付款 5、受理中 10：已付款  20：待充值  30：充值完成 100:撤消
                $addOrder->remark = ""; //备注
                $addOrder->save();

                $this->redirect('paying', 'pay', array('type' => Application_Model_PayBill::TYPE_CARD, 'id' => $addOrder->Id, 'count' => 1));
            } else {
                $this->view->message = "对不起,您选择的$money 元的卡已售完,请选择别的面值的卡号,或者联系客服.";
            }
        }
    }

    /*
     * 移动卡列表
     */

    public function cardpaylistAction() {




        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/cardpay.css');

        $this->appendScript('/js/jquery.min.js');
        $this->appendScript('/js/jquery.validate.min.js');

        $this->setTitle('我的帐户 |  移动卡充值');
        $this->appendCss('/css/home/coupon.css');


        $start = $this->getSafeParam('start');
        if (!$start)
            $start = 0;

        $status = $this->getSafeParam('status');
//        if(!$status)
//            $status=-1;

        $stime = $this->getSafeParam('stime');
        if (!$stime)
            $stime = -3;

        $etime = $this->getSafeParam('etime');
        if (!$etime)
            $etime = 1;

        $this->pageSize = 10;

        $userid = $this->currentUser()->Id;
        $this->view->cardOrders = Application_Model_PayCodeOrder::getByFilter(NULL, $userid, date('Y-m-d', strtotime("$stime months")), date('Y-m-d', strtotime("$etime months")), $status, $this->pageSize, $start, 5);

        $this->view->cardOrder = $this->view->cardOrders['list'];
        $this->view->status = $status;
    }

    public function agentpaylistAction() {
        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/alipaycode.css');

        $start = $this->getSafeParam('start');
        if (!$start)
            $start = 0;

        $this->view->list = Application_Model_AgentPay::getByFilter($this->currentUser()->Id, $start, $this->pageSize);
        $this->setTitle('我的代支付记录');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $id = $request->getParam('id');    //ID
            $type = $request->getParam('type');   //操作类型，1为取消，2为删除

            if ($type == '2') {
                //删除代充值记录
                $agent = Application_Model_AgentPay::load($id);
                if ($agent) {
                    $agent->delete();
                }
            }
        }
    }

    public function alipaycodelistAction() {
        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/alipaycode.css');


        $this->setTitle('我的帐户 |  移动卡充值');
        $this->appendCss('/css/home/coupon.css');


        $start = $this->getSafeParam('start');
        if (!$start)
            $start = 0;

        $status = $this->getSafeParam('status');
//        if(!$status)
//            $status=-1;

        $stime = $this->getSafeParam('stime');
        if (!$stime)
            $stime = -3;

        $etime = $this->getSafeParam('etime');
        if (!$etime)
            $etime = 1;

        $this->pageSize = 10;

        $userid = $this->currentUser()->Id;
        $this->view->cardOrders = Application_Model_PayCodeOrder::getByFilter(NULL, $userid, date('Y-m-d', strtotime("$stime months")), date('Y-m-d', strtotime("$etime months")), $status, $this->pageSize, $start, 10);

        $this->view->cardOrder = $this->view->cardOrders['list'];
        $this->view->status = $status;
    }

    public function forecastdetailAction() {
        $this->appendCss('/css/home/rmb.css');
        $id = $this->getSafeParam('id');
        $item = Application_Model_ingstore::load($id);
        $problemItem = Application_Model_QualityProblem::byObjectIdObjectType($id, Application_Model_DomainobjectType::ObjectType_Ing);
        $contentArr = $problemItem ? $problemItem->getContent() : "";
        $problemNum = $problemItem ? $problemItem->getNum("") : 0;
        $this->view->contentArr = $contentArr;
        $this->view->problemNum = $problemNum;
        $this->view->item = $item;
        $this->setTitle($item->Name . ' | 查看物流详情');
    }

    private function getWaybillInfo($id) {
        $bill = Application_Model_wayBillItem::load($id);
        $no = $bill->Logistics;

        $content = '';
        $isUrl = 0;
        $express = $bill->getExpressBy();
        if ($express->TrackType == Application_Model_Express::TRACK_TYPE_KUAIDI100 || $express->TrackType == Application_Model_Express::TRACK_TYPE_KUAIDI_LINK) {
            $type = $express->TrackNo;
            $content = '';
            $isUrl = $express->TrackType == Application_Model_Express::TRACK_TYPE_KUAIDI_LINK ? 1 : 0;
            if ($isUrl) {
                $content = Uuch_Util::expressUrl($type, $no);
            } else {
                $content = Uuch_Util::express($type, $no);
            }
        } else if ($express->TrackType == Application_Model_Express::TRACK_TYPE_LINK) {
            $content = '<a target="_blank" href="' . sprintf($express->TrackUrl, $no) . '">点击链接前往' . $express->name . '官网查看物流情况(单号:' . $no . ')</a>';
        } else if ($express->TrackType == Application_Model_Express::TRACK_TYPE_3TH) {
            $sg = new Uuch_SpeedPostAPI();
            $result = $sg->query($no);
            $content = '<table><tr><td>Date and Time</td><td>Location</td><td>Status</td><td>Reason</td></tr>';
            foreach ($result as $item) {
                $content .= "<tr><td>$item->dateTime</td><td>$item->location</td><td>$item->status</td><td>$item->reason</td></tr>";
            }
            $content .= '</table>';
            //$content = '<a target="_blank" href="'. sprintf($express->TrackUrl,$no) .'">点击链接查看'. $express->name .'物流情况(单号:'. $no .')</a>';
        } else if ($express->TrackType == Application_Model_Express::TRACK_TYPE_WEB || $express->TrackType == Application_Model_Express::TRACK_TYPE_MIX) {
            $content = '<a target="_blank" href="' . sprintf($express->WebUrl, $no) . '">点击链接前往' . $express->name . '官网查看物流情况(单号:' . $no . ')</a>';
        } else if ($express->TrackType == Application_Model_Express::TRACK_TYPE_UUCH) {
            $content = '抱歉,暂无物流跟踪,请联系在线客服咨询物流情况';
        }

        $this->json(array('content' => $content, 'isUrl' => $isUrl));
    }

    public function getingexpressAction() {
//        $id = $this->getSafeParam('id');
//        $type = $this->getSafeParam("type");
//        $instore = Application_Model_ingstore::load($id);
//        if($instore){
//            $expresstype = $instore->ShipTypeBy->Code;
//            $no = $instore->ShipNo;
//            $ship = $instore->ShipTypeBy;
//        }
//        if($type == 3){
//            $instore = Application_Model_Order::load($id);
//            $expresstype = $instore->logname->Code;
//            $no = $instore->LogisticsNo;
//            $ship = $instore->logname;
//        }
//        if(!$instore){
//            $this->json(array('content' => "无法获取物流信息"));
//            return ;
//        }
//        
//        $content = '';
//        $isUrl = $ship->IsUrl;
//        if ($isUrl) {
//            $content = Uuch_Util::expressUrl($expresstype, $no);
//        } else {
//            $content = Uuch_Util::express($expresstype, $no);
//        }
//
//        $this->json(array('content' => $content, 'isUrl' => $isUrl));
        $id = $this->getSafeParam('id');
        $type = $this->getSafeParam("type");
        if ($type == 3) {
            $order = Application_Model_Order::load($id);
            $name = $order->Emmis->Name;
            $no = $order->logisticsNo;
        } else {
            $instore = Application_Model_ingstore::load($id);
            $name = $instore->Emmis->Name;
            $no = $instore->ShipNo;
        }
        $cemskind = mb_convert_encoding(urldecode($name), 'GB2312', 'UTF-8');
        $cemskind = urlencode($cemskind);
        $niuMen = new Uuch_Express_NiuMen($cemskind, $no);
        $content = $niuMen->getTrackData();
        $this->json(array('content' => $content));
    }

    public function getexpressAction() {
        $id = $this->getSafeParam('id');
        $bill = Application_Model_wayBillItem::load($id);
        $no = $bill->Logistics;

        $content = '';
        $isUrl = 0;
        $express = $bill->getExpressChannelBy();
        $seen = Application_Model_WayLog::getByWayIdInteriorType($id, Application_Model_WayLog::OperateType_Seen);
        if ($express->TrackType == Application_Model_Express::TRACK_TYPE_KUAIDI100JSON) {
            $item = new Uuch_Track_KuaiDiAPI($express->trackNo, $no);
            $content = $item->query();
            if ($content) {
                $bill->affirmtransportation();      //自动上网
            } else {
                $content = "暂时查不到消息 ";
            }
        } else if ($express->TrackType == Application_Model_Express::TRACK_TYPE_3TH) {
            if ($express->Name == "新加坡EMS") {
                $sg = new Uuch_Track_SpeedPostAPI();
                $result = $sg->query($no);
                if (is_array($result) && !empty($result)) {
                    $bill->affirmtransportation();            //自动上网
                    $content = '<table><tr><td>Date and Time</td><td>Location</td><td>Status</td><td>Reason</td></tr>';
                    foreach ($result as $item) {
                        $content .= "<tr><td>$item->dateTime</td><td>$item->location</td><td>$item->status</td><td>$item->reason</td></tr>";
                    }
                } else {
                    $content = "暂时查不到消息 ";
                }
            } else {
                $sg = new Uuch_Track_ComOneExpressAPI($no);
                $result = $sg->query();
                if (is_array($result) && !empty($result)) {
                    $bill->affirmtransportation();          //自动上网
                    $content = '<table><tr><td>Date</td><td>Time</td><td>Location</td><td>Status</td></tr>';
                    foreach ($result as $item) {
                        $content .= "<tr><td>$item->date</td><td>$item->time</td><td>$item->location</td><td>$item->status</td></tr>";
                    }
                    $content .= '</table>';
                } else {
                    $content = "暂时查不到消息 ";
                }
            }
        } else if ($express->TrackType == Application_Model_Express::TRACK_TYPE_LINK) {
            $item = new Uuch_Track_SingpostAPI(sprintf($express->TrackUrl, $no));
            $result = $item->query();
            if (is_array($result) && !empty($result)) {
                $bill->affirmtransportation();      //自动上网
                $content = '<table><tr><td>Date</td><td>Description</td></tr>';
                foreach ($result as $item) {
                    $content .= "<tr><td>$item->date</td><td>$item->description</td></tr>";
                }
                $content .= '</table>';
            } else {
                $content = "暂时查不到消息 ";
            }
        } else if ($express->TrackType == Application_Model_Express::TRACK_TYPE_WEB) {
            if ($express->trackNo == "hkpost") {
                $item = new Uuch_Track_HkpostAPI(sprintf($express->TrackUrl, $no));
                $result = $item->query();
                if ($result) {
                    $bill->affirmtransportation();      //自动上网
                    if (is_array($result) && !empty($result)) {
                        $content = '<table><tr><td>Date</td><td>Location</td><td>Content</td></tr>';
                        foreach ($result as $item) {
                            $content .= "<tr><td>$item->date</td><td>$item->location</td><td>$item->content</td></tr>";
                        }
                        $content .= '</table>';
                    } else {
                        $content = $result;
                    }
                } else {
                    $content = "暂时查不到消息 ";
                }
            } else if ($express->trackNo == "singpost") {
                $item = new Uuch_Track_SingpostAPI(sprintf($express->TrackUrl, $no));
                $result = $item->query();
                if (is_array($result) && !empty($result)) {
                    $bill->affirmtransportation();      //自动上网
                    $content = '<table><tr><td>Date</td><td>Description</td></tr>';
                    foreach ($result as $item) {
                        $content .= "<tr><td>$item->date</td><td>$item->description</td></tr>";
                    }
                    $content .= '</table>';
                } else {
                    $content = "暂时查不到消息 ";
                }
            }
        }
        if ($seen) {
            $this->json(array('content' => $content, 'isUrl' => $isUrl, 'seeDate' => $seen->DateCreated, 'operator' => $seen->Operator, 'type' => 1));
        } else {
            $this->json(array('content' => $content, 'isUrl' => $isUrl));
        }
    }

    public function selectstoreAction() {
        $id = $this->getSafeParam('itemid');
        $isSelected = $this->getSafeParam('selected');
        $item = Application_Model_StoreItem::load($id);
        if ($item->Userid != $this->currentUser()->Id) {
            $this->json(-1);
            return;
        }
        $item->IsSelected = $isSelected;
        $item->save();
        $selects = Application_Model_StoreItem::getMySelect($this->currentUser()->Id);
        $weight = Application_Model_StoreItem::getSumWeight($selects);
        $this->json(array('count' => count($selects), 'weight' => $weight));
    }

    public function newaddressAction() {
        $userid = $this->currentUser()->id;
        $newItem = new Application_Model_address();
        $newItem->state = $this->getSafeParam("state"); //所在国家
        //$newItem->province=$this->getSafeParam("province");
        //$newItem->city=$this->getSafeParam("City");
        $newItem->street = $this->getSafeParam("street");
        $newItem->comment = "";
        $newItem->postcode = $this->getSafeParam("postCode");
        $newItem->linkMan = $this->getSafeParam("linkMan");
        $newItem->mobile = $this->getSafeParam("mobile");
        //$newItem->phone=$this->getSafeParam("phone");
        $newItem->userId = $userid;
        $newItem->default = time(); //默认值
        $newItem->type = Application_Model_address::Type_Foreign;
        $newItem->save();
        $this->view->newAddressId = $newItem->Id;

        $this->setcultfee($newItem->Id);
        $this->render('cultfee');
    }

    /**
     * 根据所选国家，计算运费 
     */
    public function cultfeeAction() {
        $addressId = $this->getSafeParam('address');
//        $isWooden = $this->getSafeParam("isWooden");
//        $this->setcultfee($addressId,$isWooden);
        $this->setcultfee($addressId);
    }

    private function setcultfee($addressId) {
        $userid = $this->currentUser()->Id;
        $items = Application_Model_StoreItem::getMySelect($userid);
        $this->view->volumeWeight = Application_Model_StoreItem::getSumVolumeWeight($items);
        $this->view->weight = Application_Model_StoreItem::getSumWeight($items);
//        $this->view->isWooden = $isWooden;
        $this->view->bagWeight = Uuch_Util::getPackage($this->view->weight);
        $this->view->SumWeight = $this->view->bagWeight + $this->view->weight;
        $isReceive = 0;
//        foreach ($items as $itemVal) {
//            if($itemVal->Barcode == Application_Model_StoreItem::User_Barcode){
//                $isReceive = 1;
//            }
//        }
//        $isReceive = ($isReceive == 1 && count($items)==1)?1:0;
        $this->view->items = $items;
        $this->view->isReceive = $isReceive;
        $address = Application_Model_address::load($addressId);
        $this->view->city = $address->getCityBy();
        $this->view->prices = Application_Model_ExpressPrice::getPricesByCity($address->State);
        $this->view->isZipRemoteFee = Application_Model_RemoteFee::byStateIdZip($address->State, $address->Postcode);
        $isEast = FALSE;
        if ($address->State == Application_Model_city::Malaysia) {
            $isEast = Application_Model_RemoteFee::EastOrWestern($address->Postcode);
        }
        $isAbCoupon = false;
        if ($address->State == 1) { //美国
            $couponSearch1 = new Application_Model_Filter_CouponSearch();
            $couponSearch1->userId = $userid;
            $couponSearch1->batchNo = "UsDHLAb";
            $AbCoupon = Application_Model_Coupon::getOne($couponSearch1);
            $isAbCoupon = $AbCoupon ? true : false;
        }
        $this->view->isAbCoupon = $isAbCoupon;
        $this->view->isEast = $isEast;
        $this->_helper->layout->disableLayout();
    }

    public function waybillcreateAction() {
        $this->appendCss('/css/home/order.css');
        $this->setTitle('提交国际运单');
        $userid = $this->currentUser()->Id;
        $items = Application_Model_StoreItem::getMySelect($userid);
        if (count($items) == 0) {
            $this->redirect('mystore', 'member');
            return;
        }

        $this->view->volumeWeight = Application_Model_StoreItem::getSumVolumeWeight($items);
        $this->view->weight = Application_Model_StoreItem::getSumWeight($items);
        $this->view->itemCount = count($items);

        $this->view->bagWeight = Uuch_Util::getPackage($this->view->weight);
        $this->view->SumWeight = $this->view->bagWeight + $this->view->weight;
        $this->view->items = $items;

        $address = Application_Model_address::getByUserIdType($userid);
        $this->view->address = array_reverse(Uuch_Util::quickSort($address, 'Id'));
        $isEast = FALSE;
        if (count($address) == 0) {
            $this->view->default = new Application_Model_address(array('State' => 1));
            $this->view->hasAddress = false;
            $this->view->isEuro = FALSE;
        } else {
            $this->view->default = $address[count($address) - 1];
            $city = $this->view->default->getCityBy();
            $this->view->isEuro = ($city->AreaCode >= 7 && $city->AreaCode <= 10);
            $this->view->hasAddress = TRUE;
            $this->view->isZipRemoteFee = Application_Model_RemoteFee::byStateIdZip($this->view->default->State, $this->view->default->Postcode);
            if ($this->view->default->State == Application_Model_city::Malaysia) {
                $isEast = Application_Model_RemoteFee::EastOrWestern($this->view->default->Postcode);
            }
        }

        $this->view->prices = Application_Model_Express::getPricesByCity($this->view->default->State);
        $isAbCoupon = false;
        if ($this->view->default->State == 1) { //美国
            $couponSearch1 = new Application_Model_Filter_CouponSearch();
            $couponSearch1->userId = $userid;
            $couponSearch1->batchNo = "UsDHLAb";
            $AbCoupon = Application_Model_Coupon::getOne($couponSearch1);
            $isAbCoupon = $AbCoupon ? true : false;
        }
        $words = array();
        for ($i = 0; $i < 26; $i++) {
            $words [] = chr(65 + $i);
        }
        $cnShipFee = 0;
        $isReceive = 0;
        $isFragile = 0;
        foreach ($items as $item) {
            $cnShipFee += $item->CnShipFee;
            if (($item->ItemType & Application_Model_StoreItem::TYPE_Fragile) == Application_Model_StoreItem::TYPE_Fragile) {
                $isFragile = 1;
            }
//            if($item->Barcode == Application_Model_StoreItem::User_Barcode){
//                $isReceive = 1;
//            }
        }
//        $isReceive = ($isReceive==1&&count($items)==1)?1:0;
        /* 马年端午活动开始 */
        $this->view->isHorseWuanwu = 0;
        if (array_key_exists("activityCode", $_COOKIE)) {
            if ("75b03664cc9d8ef68f0ec1dc37a761e8" == Uuch_Util::decryptString($_COOKIE["activityCode"]) && date("Y-m-d") >= Application_Model_RechargeBill::RechargeActivityStart && date("Y-m-d") <= Application_Model_RechargeBill::RechargeActivityEnd) {
                $this->view->isHorseWuanwu = 1;
            }
        }
        /* 马年端午活动结束 */
        $this->view->fragileFee = $this->view->SumWeight >= 5000 ? 20 : 10;
        $this->view->isFragile = $isFragile;
        $this->view->words = $words;
        $this->view->cnShipFee = $cnShipFee;
        $couponSearch = new Application_Model_Filter_CouponSearch();
        $couponSearch->userId = $userid;
        $couponSearch->status = Application_Model_Coupon::STATUS_OK;
        $couponSearch->useScope = Application_Model_Coupon::Scope_Waybill;
        $this->view->coupons = Application_Model_Coupon::getByUser($couponSearch);
        $this->view->isReceive = $isReceive;
        $this->view->isEast = $isEast;
        $this->view->isAbCoupon = $isAbCoupon;
    }

    public function waybillsubmitAction() {
        $shipType = $this->getSafeParam('shipType');
        $ship = Application_Model_Express::load($shipType);
        $userid = $this->currentUser()->Id;
        $items = Application_Model_StoreItem::getMySelect($userid);

        if (count($items) == 0) {
            $this->redirect('mystore', 'member');
            return;
        }

        $cnShipFee = 0;
        $isReceive = 0;
        foreach ($items as $item) {
             //保存操作时间
            $item->operatedate=date('Y-m-d H:i:s',time());
            $item->save();
            if ($item->State == Application_Model_StoreItem::STATUS_Sended) {
                $this->redirect('mystore', 'member');
                return;
            }
            $cnShipFee += $item->cnShipFee;
//            if($item->Barcode == Application_Model_StoreItem::User_Barcode){
//                $isReceive = 1;
//            }
        }
//        $isReceive = ($isReceive==1&&count($items)==1)?1:0;

        $productWeight = Application_Model_StoreItem::getSumWeight($items);
        $volumWeight = Application_Model_StoreItem::getSumVolumeWeight($items);

        $bagWeight = Uuch_Util::getPackage($productWeight);

        $weight = 0;
        $isVolume = FALSE;

        if ($ship->IsVolume && $volumWeight > $productWeight + $bagWeight) {
            $weight = $volumWeight;
            $isVolume = TRUE;
        } else {
            $weight = $productWeight + $bagWeight;
        }
        $fragile = ($productWeight + $bagWeight) > 5000 ? 20 : 10;
        $addressId = $this->getSafeParam('addressId');
        $address = Application_Model_address::load($addressId);

        $ep = Application_Model_ExpressPrice::getPriceByExpressAndCity($ship->Id, $address->State);
        $shipFee = $ep->getMoneyByweight($weight);
//        if($isReceive){
//            $shipFee = 0.01;
//        }
        //$shipMoney = Application_Model_shipFeeConfig::getMoney($address->State, $ship->Id, $weight);

        $couponNo = $this->getSafeParam('couponno');
        $password = $this->getSafeParam('password');
        $discount = 0;
        $coupon = NULL;
        if ($couponNo != '0') {
            $coupon = Application_Model_Coupon::getByNo($couponNo);
            $couponResult = $coupon->Validate($userid, $shipFee, $password, $shipType);
            if ($couponResult->result) {
                $discount = $couponResult->discount;
                $coupon->Status = Application_Model_Coupon::STATUS_USED;
                $coupon->UseType = Application_Model_Coupon::useType_WayBill;
            }
        }
        $serviceFee = 0; //暂时不收服务费
        //偏远费
        $foRemoteFee = 0;
        $isRemoteFee = Application_Model_RemoteFee::byStateIdZip($address->State, $address->Postcode);
        if ($isRemoteFee && $ship->IsRemoteFee) {
            $foRemoteFee = Application_Model_RemoteFee::remoteFee;
        }

        $woodenFee = $this->getSafeParam('isWooden') ? 50 : 0;
        $compressFee = $this->getSafeParam('isCompress') ? 20 : 0;
        $removalFee = $this->getSafeParam('isNoLogo') ? 20 : 0;
        $fragileFee = $this->getSafeParam("isFragile") ? $fragile : 0;
        $premiumFee = 0;
        $premiumValue = 0;
        if ($this->getSafeParam('isPremium') == '1') {
            $premiumValue = $this->getSafeParam('PremiumValue');
            if ($premiumValue != '') {
                $premiumFee = $premiumValue * Application_Model_Config::getPremiumRate()->Value;
            }
        }

        $shipMoney = $shipFee - $discount + $ship->ReportFee + $serviceFee + $cnShipFee + $woodenFee + $removalFee + $compressFee + $fragileFee + $premiumFee + $foRemoteFee;
        if ($shipMoney < 0) {
            $shipMoney = 0;
        }

        if($shipMoney == 0 && $discount > 0){
            $this->view->MESSAGE ="该订单金额太小,不能使用优惠券!";
            $this->view->BUTTON_TEXT = '返回';
            $this->view->URL = '';
            $this->renderScript('/message.phtml');
            return;
        }

        /* 2014国庆活动开始 */
        if (time() > strtotime('2014-10-01') && time() < strtotime('2014-10-08')) {
            if ($ep->firstPrice >= 80) {                    
                $activityDiscount = 8;
            } else {
                $activityDiscount = 4;
            }
            $shipMoney = $shipMoney - $activityDiscount;
        }
        /* 2014国庆活动结束 */

        $newItem = new Application_Model_wayBillItem();
        $wayCode = Uuch_Util::getWayCode();
        $newItem->billNo = $wayCode; //运单号
        $newItem->dateCreated = date('Y-m-d H:i:s'); //创建日期
        $newItem->status = Application_Model_wayBillItem::STATUS_WaitPay; //状态 0:等待付款 1：受理中(正在发货) 2:已经发货 100：已经完成 -1:取消 -2:海关退货；
        $newItem->userId = $userid; //用户ID
        $newItem->interior = Application_Model_wayBillItem::Interior_WaitPay;
        $newItem->lastdate = $this->now();
        $newItem->IsVolume = $ship->IsVolume;
        $newItem->setAllWeight($weight, $bagWeight, $productWeight, $volumWeight);

        $newItem->shipType = $ship->Id; //运送方式
        $newItem->ExpressId = $ship->Id;
        $newItem->shipFeeconfig = $ep->Id; //
        $newItem->setAddress($address);

        $newItem->isNoLogo = $this->getSafeParam('isNoLogo') ? '1' : '0'; //是否去掉吊牌，Logo等
        $newItem->isNoSkin = $this->getSafeParam('isNoSkin') ? '1' : '0'; //是否要去掉不必要包装
        $newItem->isCompress = $this->getSafeParam('isCompress') ? '1' : '0'; //是否要压缩抽气
        $newItem->isWooden = $this->getSafeParam('isWooden') ? '1' : '0';

        $newItem->dutyNo = $this->getSafeParam('dutyNo'); //税号

        $newItem->Remark = $this->getSafeParam('remark');

        $newItem->setAllMoney($shipMoney, $shipFee, $ship->ReportFee, $discount, $serviceFee);
        $newItem->save();

        $waybillCount = Application_Model_wayBillItem::getCountByUserId($userid);
        if ($waybillCount == 1) {
            $accountItem = Application_Model_UserAccount::addAccount($userid);
            $accountItem->TaskExchangeScore(Application_Model_Task::TASK_WAYBILL);
        }

        if ($couponNo != '0' && $discount > 0) {
            $coupon->Relevance = $newItem->Id;
            $coupon->UseTime = $this->now();
            $coupon->save();
        }

        foreach ($items as $item) {
            $item->WayId = $newItem->Id;
            $item->State = Application_Model_StoreItem::STATUS_Sended;
            $item->IsSelected = FALSE;
            $item->save();
            $newItem->addItem($item->Id);
            $newItem->save();
        }

        //添加费用信息
        $newItem->addFee(Application_Model_FeeType::EstimateShipFee, $shipFee);
        $newItem->addFee(Application_Model_FeeType::CnShipFee, $cnShipFee);
        $newItem->addFee(Application_Model_FeeType::CouponFee, $discount * -1);
        $newItem->addFee(Application_Model_FeeType::ReportFee, $ship->ReportFee);
        $newItem->addFee(Application_Model_FeeType::OperationFee, $serviceFee);
        $newItem->addFee(Application_Model_FeeType::EstimateSum, $shipMoney);
        if ($woodenFee > 0) {
            $newItem->addFee(Application_Model_FeeType::WoodenFee, $woodenFee);
        }

        if ($compressFee > 0) {
            $newItem->addFee(Application_Model_FeeType::VacuumSeviceFee, $compressFee);
        }

        if ($removalFee > 0) {
            $newItem->addFee(Application_Model_FeeType::RemovalFee, $removalFee);
        }

        if ($fragileFee > 0) {
            $newItem->addFee(Application_Model_FeeType::FragileFee, $fragileFee);
        }

        if ($premiumFee) {
            $newItem->addFee(Application_Model_FeeType::RatePremiumFee, $premiumFee);
            $newItem->addFee(Application_Model_FeeType::PremiumValue, $premiumValue);
        }

        if ($isRemoteFee && $ship->IsRemoteFee) {
            $newItem->addFee(Application_Model_FeeType::RemoteFee, $foRemoteFee);
        }

        $reportValue = $this->getSafeParam('reportValue');
        if ($reportValue) {
            $newItem->addFee(Application_Model_FeeType::ReprotValue, $reportValue);
        }
        
         /* 2014国庆活动开始 */
        if (time() > strtotime('2014-10-01') && time() < strtotime('2014-10-08')) {
            if ($activityDiscount > 0) {
                $newItem->addFee(Application_Model_FeeType::ActivityDiscountCash, $activityDiscount);
            }
        }
        /* 2014国庆活动结束 */

        //添加重量信息
        $newItem->addWeight(Application_Model_WeightType::ProductWeight, $productWeight);
        $newItem->addWeight(Application_Model_WeightType::BagWeight, $bagWeight);
        $newItem->addWeight(Application_Model_WeightType::EstimateWeight, $weight);
        $newItem->addWeight(Application_Model_WeightType::EstimateVolume, $volumWeight);

        $this->redirect('paying', 'pay', array('type' => Application_Model_PayBill::TYPE_WAYBILL, 'id' => $newItem->Id, 'count' => 1));
    }

    public function addressAction() {
        $this->setTitle('我的收货地址');
        $this->appendCss('/css/home/addressbook.css');
        $this->view->address = Application_Model_address::getbyuid($this->currentUser()->Id);
        $words = array();
        for ($i = 0; $i < 26; $i++) {
            $words [] = chr(65 + $i);
        }
        $this->view->city = Uuch_Util::getCurrentCity();
        $this->view->words = $words;
    }

    public function deladdressAction() {
        $id = $this->getSafeParam('id');
        $address = Application_Model_address::load($id);
        if ($address->UserId == $this->currentUser()->Id) {
            $address->delete();
        }
        $this->redirect('address', 'member');
    }

    public function saveaddressAction() {
        $userid = $this->currentUser()->id;
        $newItem = new Application_Model_address();
        $newItem->state = $this->getSafeParam("state"); //所在国家
        //$newItem->province=$this->getSafeParam("province");
        //$newItem->city=$this->getSafeParam("City");
        $newItem->street = $this->getSafeParam("street");
        $newItem->comment = "";
        $newItem->postcode = $this->getSafeParam("postcode");
        $newItem->linkMan = $this->getSafeParam("linkMan");
        $newItem->mobile = $this->getSafeParam("mobile");
        //$newItem->phone=$this->getSafeParam("phone");
        $newItem->userId = $userid;
        $newItem->default = time(); //默认值
        $newItem->type = Application_Model_address::Type_Foreign;
        $newItem->save();
        $this->redirect('address', 'member');
    }

    /**
     * 检测邮箱是否存在
     */
    public function checkemailAction() {
        $email = $this->getSafeParam("email");
        if (Application_Model_User::getByEmail($email)) {
            $this->json(1);
        } else {
            $this->json(0);
        }
    }

    /**
     * 会员更换邮箱
     */
    public function emailAction() {
        $this->appendCss('/css/home/personal.css');
        $this->appendScript('/js/My97DatePicker/WdatePicker.js');
        $email = $this->getSafeParam("email");
        $email2 = $this->getSafeParam("email2");
        if ($email && $email2 && $email == $email2) {
            $pregEmail = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
            $isCheckEmail = preg_match($pregEmail, $email);
            if ($isCheckEmail == 0) {
                $this->json(array('type' => 0));
                return;
            }
            if (!Application_Model_User::getByEmail($email)) {
                $user_item = $this->currentUser();
                if ($user_item->State == Application_Model_User::STATUS_New || $user_item->State == "") {
                    $user = Application_Model_user::load($user_item->Id);
                    $user->Email = $email;
                    $user->State = Application_Model_User::STATUS_New;
                    $user->save();
                    /* $userid = $user->Id;
                      $key = md5(md5($userid . time()) * rand(10000, 99999));
                      $userKey = Application_Model_UserKey::getByUserId($userid);
                      if ($userKey == null) {
                      $userKey = new Application_Model_UserKey();
                      }
                      $userKey->uid = $userid;
                      $userKey->EmailKey = $key;
                      $userKey->EmailTime = date('Y-m-d 00:00:00', time() + 3600 * 24 * 1); //结束时间为第二天0点
                      $userKey->save();
                      $receive = array('email' => $email, 'name' => $email);
                      $link = "http://old.uuch.com/user/active?uid=".$user->Id."&MjkzNzM=".$key;
                      $this->sendUserRegisterdMail($receive,$link,$user->NikeName); */
                    $this->setUser($email, 0);
                    $this->json(array('type' => 1, 'uid' => $user->id));
                } else {
                    $this->json(array('type' => 0));
                }
            } else {
                $this->json(0);
            }
        }
    }

    /**
     * 激活邮箱
     */
    public function activationAction() {
        $uid = $this->getSafeParam("uid");
        if ($uid) {
            $user_item = Application_Model_User::load($uid);
        } else {
            $user_item = $this->currentUser();
        }
        if ($user_item->State == Application_Model_User::STATUS_New || $user_item->State == "") {
            $userid = $user_item->Id;
            $email = $user_item->Email;
            $key = md5(md5($userid . time()) * rand(10000, 99999));
            $userKey = Application_Model_UserKey::getByUserId($userid);
            if ($userKey == null) {
                $userKey = new Application_Model_UserKey();
            }
            $userKey->uid = $userid;
            $userKey->EmailKey = $key;
            $userKey->EmailTime = date('Y-m-d 00:00:00', time() + 3600 * 24 * 1); //结束时间为第二天0点
            $userKey->save();
            $receive = array('email' => $email, 'name' => $email);
            $link = "http://old.uuch.com/user/active?uid=" . $userid . "&MjkzNzM=" . $key;
            $this->sendUserRegisterdMail($receive, $link, $user_item->NikeName);
            $this->json(0);
        } else {
            $this->json(1);
        }
    }

    /**
     * 会员注册 - 发邮件
     */
    public function sendUserRegisterdMail($receive, $link, $name) {
        $title = "悠奇账号：" . $name . "注册成功；请激活安全邮箱";
        $body = "尊敬的悠奇用户：

                    " . $name . "您好！
                
                    感谢您注册悠奇网。

                                        为保证您方便快捷的使用悠奇服务，我们建议您进行邮箱验证。请点击下面的链接确认邮箱

                                        $link
                                        如果您点击此链接后发现它可能已损坏，请复制此链接并将其粘贴到新的浏览器窗口中。

                                        感谢您使用 uuch！

                                        uuch悠奇网敬上

                                        请不要回复此邮件。如果您要与UUCH小组联系，请登录您的帐户，点击任何页面顶部的“帮助”，然后点击“帮助中心”底部的“与我们联系”。
                ";

        return Uuch_Mail::SendMail($title, $body, $receive);
    }

    public function receiveAction() {
        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/replacerecharge.css');

        $this->appendScript('/js/jquery.min.js');
        $this->appendScript('/js/jquery.validate.min.js');
        $userId = $this->currentUser()->Id;
        if (!$userId) {
            $this->redirect('login', 'user');
            return;
        }
        if ($this->getRequest()->isPost()) {
            $type = $this->getSafeParam("type");
            $barcode = Application_Model_StoreItem::User_Barcode;
            $storeItem = Application_Model_StoreItem::getByUserIdBarcode($userId, $barcode);
            $typeNames = Application_Model_StoreItem::getTypeNames();
            if (!$storeItem) {
                /**
                 * 添加仓库记录
                 */
                $item = new Application_Model_StoreItem();
                $item->ProductName = "会员礼物-" . $typeNames[$type]["name"];
                $item->StoreId = "88" . $type;
                $item->DateInStore = $this->now();
                $item->Quantity = 1;
                $item->State = Application_Model_StoreItem::STATUS_InStored;
                $item->LogisticsName = "悠奇专线";
                $item->Logistics = "88888888";
                $item->OrderNo = $item->Logistics;
                $item->Userid = $userId;
                $item->Weight = 1;
                $item->Createdate = $this->now();
                $item->VolumeWeight = 1;
                $item->BignessType = 0;
                $item->IsBrand = 0;
                $item->IsSpecific = 0;
                $item->CanVacuum = 0;
                $item->IsEmbargo = 0;
                $item->Barcode = Application_Model_StoreItem::User_Barcode . Application_Model_StoreItem::createBarcode();
                $item->Image = $typeNames[$type]["img"];
                $item->Image = str_replace("http://old.uuch.com", "", $item->Image);
                $item->ItemType = 0;
                $item->Remark = "会员卡";
                $item->Intype = "悠奇专线";
                $item->OperateName = Uuch_Util::getUserNikeName();
                $item->Interior = Application_Model_StoreItem::Interior_InStored;
                $item->Isdelete = 0;
                $item->IsProblem = 0;
                $item->LocationNo = "LW-11";
                $item->save();
                /**
                 * 添加优惠券
                 */
                Application_Model_Coupon::addCoupon($userId, date("Y-m-d H:i:s", time() + 90 * 86400), null, 100, 10, null, Application_Model_Coupon::Type_All, Application_Model_Coupon::Scope_Waybill, date("Y-m-d H:i:s"), "ReceiveUser", "领取会员卡奖励");

                /**
                 * 添加一元体验金
                 */
                $userItem = Application_Model_UserAccount::load($userId);
                $beforeMoney = $userItem->money;
                $userItem->money = $userItem->money + 1;
                $afterMoney = $userItem->money;
                $userItem->save();

                $history = new Application_Model_UserAccountHistory();
                $history->type = 0;
                $history->beforeMoney = $beforeMoney;
                $history->afterMoney = $afterMoney;
                $history->comment = "领取会员卡赠送1元体验金";
                $history->dateCreated = date("Y-m-d H:i:s");
                $history->relaseId = "1";
                $history->State = Application_Model_UserAccountHistory::STATE_MONEY;
                $history->accountId = $userId;
                $history->save();
                $this->view->giftName = $typeNames[$type]["name"];
                $this->view->ma = 1;
                $user = Application_Model_User::load($userId);
                $financeData = array(
                    'transaction_number' => '',
                    'trader' => 'backend-account-cr',
                    'customer_id' => $userId,
                    'member' => 'admin',
                    'amount' => 1,
                    'currency' => 'CNY',
                    'customer_name' => $user->nikename,
                    'rate' => '1',
                    'rate_amount' => '0',
                    'period_start' => $beforeMoney,
                    'period_end' => $beforeMoney,
                    'business_type' => 'tiyanjing',
                    'order_sn' => '',
                    'remark' => '',
                    'created_at' => date('Y-m-d H:i:s')
                );
                $this->_addFinance($userItem, $financeData);
                $financeData['period_end'] = $afterMoney;
                $financeData['trader'] = 'account-number-dr';
                $this->_addFinance($userItem, $financeData);
            } else {
                $this->view->ma = 0;
            }
        }
    }

    protected function _addFinance($account, $data) {
        require_once(APPLICATION_PATH . '/../library/finance/General.php');
        $api = new General($data['amount'], $account);
        $api->setFields($data);
        $api->addTransaction();
    }

    public function receivegradeAction() {
        $userId = $this->currentUser()->Id;
        if (!$userId) {
            $this->redirect('login', 'user');
            return;
        }
        $accountItem = Application_Model_UserAccount::addAccount($userId);
        $result = $accountItem->getIsReceivePrivilege();
        $reward = $accountItem->GradeReward;
        $this->json(array("type" => $result, "reward" => $reward));
    }

    /* 用户投诉界面 */

    public function complainAction() {
        $this->appendCss('/css/home/personal.css');
        $this->appendScript('/js/My97DatePicker/WdatePicker.js');
    }

    /**
     * 记录用户的投诉
     */
    public function complaintsAction() {
        $userId = $this->getSafeParam("userId");
        $res = Application_Model_Complaints::queryByUserid($userId);
        if ($res) {
            if (strtotime($res[0]->CreateTime) > time() - 30) {
                $this->json(2);
                exit();
            }
        }
        $title = $this->getSafeParam("title");
        $content = $this->getSafeParam("content");
        $item = new Application_Model_Complaints();
        $item->UserId = $userId;
        $item->Title = $title;
        $item->CreateTime = date("Y-m-d H:i:s");
        $item->Content = $content;
        $item->save();
        $this->json(1);
    }

    public function usstoreAction() {
        $this->setTitle('我的美国仓');
        $this->appendScript('/js/jquery.min.js')->appendScript('/js/clip/zeroclipboard.js');
        $this->appendCss('/css/Share.css'); //    
        $this->appendCss('/css/home/warehouse.css'); //   

        $this->view->storeAddress = Application_Model_Config::getStoreAddress()->Value;
    }

    public function usstorelistAction() {
        $this->setTitle('我的仓库 | 您的金牌仓库管家');
        $this->appendCss('/css/Share.css'); //    
        $this->appendCss('/css/home/warehouse.css');
        $this->appendScript('/js/jquery.min.js');

        $start = $this->getSafeParam('start');
        if (!$start) {
            $start = 0;
        }

        $userid = $this->currentUser()->Id;
        $this->view->stores = Application_Model_StoreItem::getMyStore($userid, $this->pageSize, $start);
        $selected = Application_Model_StoreItem::getMySelect($userid);

        $this->view->selected = array('count' => count($selected), 'weight' => Application_Model_StoreItem::getSumWeight($selected));
        $this->view->storelist = $this->view->stores['list'];
    }

    public function transferAction() {
        $this->setTitle('线下转账信息填写');
        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/replacerecharge.css');
        $this->appendScript('/js/jquery.min.js');
        $this->view->type = $this->getSafeParam('type');
        $this->view->unitAll = Application_Model_Remittance::arrUnitAll();
    }

    public function westernunionAction() {
        $this->setTitle('西联汇款信息填写');
        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/replacerecharge.css');
        $this->appendScript('/js/jquery.min.js');
        $this->view->type = $this->getSafeParam('type');
    }

    /**
     * 把客户提交的汇款信息入数据库
     */
    public function transferprocessAction() {
        $remittanceParty = $this->getSafeParam("remittanceParty");
        $remittanceName = $this->getSafeParam("remittanceName");
        $dealNo = $this->getSafeParam("dealNo");
        $remittanceCountry = $this->getSafeParam("remittanceCountry");
        $monitoring = $this->getSafeParam("monitoring");
        $bank = $this->getSafeParam("bank");
        $stime = $this->getSafeParam("stime");
        $money = $this->getSafeParam("money");
        $moneyUnit = $this->getSafeParam("moneyunit");
        //$file = $this->getSafeParam("file");
        $userId = $this->getSafeParam("userId");
        if (($remittanceParty || $monitoring || $dealNo) && $remittanceName && ($bank || $remittanceCountry) && $stime && $money && $userId) {
            $opt = new Application_Model_Remittance();
            if ($_FILES["file"]['name'] != '') {
                if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 2000000)) {
                    if ($_FILES["file"]["error"] > 0) {
                        //文件上传错误
                        $this->content('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script type="text/javascript">alert("文件格式错误");location.href="/member/transfer"</script>');
                        exit();
                    } else {
                        //存放于临时目录中的文件名
                        $temp_file_name = $_FILES["file"]["name"];
                        //默认为png格式
                        $file_type = 'png';
                        //获取图片的格式后缀名
                        $arr = explode(".", $temp_file_name);
                        $file_type = $arr[1];
                        //临时用户ID，用于左边填充0，补足9位。
                        $temp_id = $userId;
                        $temp_id = sprintf("%09d", $temp_id);
                        //1级目录
                        $l1 = date("Y-m-d") . "remittance";
                        //文件名                           
                        $file_name = date("YmdHis") . $userId . "." . $file_type;
                        $dir = "data/$l1/";
                        $create_file = Uuch_Util::create_folders($dir);
                        //存放文件到data/avatar目录中
                        move_uploaded_file($_FILES["file"]["tmp_name"], $dir . $file_name);
                        $opt->Picture = $dir . $file_name;
                    }
                } else {
                    //文件格式错误
                    $this->content('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script type="text/javascript">alert("文件格式错误");location.href="/member/transfer"</script>');
                    exit();
                }
            }
            if ($remittanceParty) {
                $opt->BankCard = $remittanceParty;
                $opt->Type = 0;
                $opt->MoneyUnit = $moneyUnit;
                if ($dealNo) {
                    $opt->DealNo = $dealNo;
                } else {
                    $this->content('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script type="text/javascript">alert("很抱歉！提交汇款信息失败");location.href="/member/transfer"</script>');
                    exit();
                }
            } else {
                $opt->BankCard = "西联汇款";
                $opt->Type = 1;
                $opt->MoneyUnit = Application_Model_Remittance::Unit_USD;
                if ($monitoring) {
                    $opt->DealNo = $monitoring;
                } else {
                    $this->content('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script type="text/javascript">alert("很抱歉！提交汇款信息失败");location.href="/member/transfer"</script>');
                    exit();
                }
            }
            $opt->RealName = $remittanceName;
            $opt->Money = $money;
            if ($bank) {
                $opt->Bank = $bank;
            } else {
                $opt->Bank = $remittanceCountry;
            }
            $opt->DateCreated = date("Y-m-d H:i:s");
            $opt->TransferTime = $stime;
            $opt->UserId = $userId;
            $opt->status = Application_Model_Remittance::STATUS_UNTREATED;
            $opt->save();
            $this->content('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script type="text/javascript">window.location.href="/member/transfer?type=success";</script>');
            exit();
        } else {
            $this->content('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script type="text/javascript">alert("很抱歉！提交汇款信息失败");location.href="/member/transfer"</script>');
            exit();
        }
    }

    public function judgedealnoAction() {
        $dealNo = $this->getSafeParam("dealNo");
        if ($dealNo) {
            $result = Application_Model_Remittance::getByDealNo($dealNo);
            if ($result) {
                $this->json(1);
            } else {
                $this->json(0);
            }
        } else {
            $this->json(0);
        }
    }

    public function problemshowAction() {
        $orderId = $this->getSafeParam("orderId");
        $orderItem = Application_Model_Order::load($orderId);
        $problemItem = Application_Model_problem::byissue($orderId, Application_Model_problem::TYPE_ORDER);
        $arrProblem = array();
        if ($problemItem) {
            foreach ($problemItem as $key => $pbVal) {
                $arrProblem[$key]["issueetype"] = $pbVal->Issuetype;
                $arrProblem[$key]["content"] = htmlspecialchars($pbVal->Content);
                $arrProblem[$key]["dateCreated"] = $pbVal->DateCreated;
                $arrProblem[$key]["userName"] = $pbVal->User->NikeName;
                $arrProblem[$key]["userId"] = $pbVal->Userid;
            }
        }
        $status = false;
        if ($orderItem->Status == Application_Model_Order::STATUS_CANCEL || $orderItem->Status == Application_Model_Order::STATUS_INSTORE) {
            $status = true;
        }
        $this->json(array("type" => 1, "arrProblem" => $arrProblem, "status" => $status));
    }

    public function addorderpbAction() {
        $orderProblemId = $this->getSafeParam("orderProblemId");
        $content = $this->getSafeParam("content");
//        $this->json($content);
        $orderItem = Application_Model_Order::load($orderProblemId);
        if ($orderItem) {
            $orderItem->Problem = Application_Model_Order::Problem_User;
            $orderItem->save();
            Application_Model_problem::addProblem($orderItem->UserId, $orderProblemId, Application_Model_problem::TYPE_ORDER, Application_Model_problem::SUE_USER, null, $content);
            $this->json(1);
        } else {
            $this->json(0);
        }
    }

    public function editstorenameAction() {
        $id = $this->getSafeParam("id");
        $remarkName = $this->getSafeParam("remarkName");
        if ($id) {

            $storeItem = Application_Model_StoreItem::load($id);
            if ($storeItem->Userid != $this->currentUser()->Id) {
                $this->json(0);
            } else {
                $storeItem->RemarkName = htmlentities($remarkName);
                $storeItem->save();
                $this->json(1);
            }
        } else {
            $this->json(0);
        }
    }

}